<?php
require_once(dirname(__FILE__).'/../config/UCConfMacro.php');

	/**
	 * UCFuncUtils.php
	 * SDO UC项目公共函数库
	 *
	 * Copyright (c) 2010 snda.com - Web Development Center
	 * @authos: Gu Shougang <gushougang@snda.com>
	 */

	/**
	 * 通过http接口获取数据
	 * @param string $requestURL 请求地址
	 * @param mixed $params 页面请求参数列表
	 * @param string $cookiePath Cookie存储路径
	 * @param int $step 请求方式: 0-curl; 1-Socket; 2-file_get_contents();
	 * @param int $timeout 请求超时时间, 单位s, 默认值5.
	 * @return mixed;
	 */
	function get_http_data($requestURL, $params = array(), $cookiePath = '', $step = 0, $timeout = 5)
	{
		switch($step)
		{
			case 0:
				if(extension_loaded('curl'))
				{
					$post = '';
					$postUrl = parse_url($requestURL);

					//$params['post'] = FALSE;
					$params['return'] = TRUE;
					$params['cookie'] = $cookiePath;

					$ch = curl_init();
					if($postUrl['scheme'] == 'https');
					{
						curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
						curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
						curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
					}
					curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
					curl_setopt($ch, CURLOPT_URL, $requestURL);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, $params['return']);
					curl_setopt($ch, CURLOPT_COOKIEJAR, $params['cookie']);
					curl_setopt($ch, CURLOPT_COOKIEFILE, $params['cookie']);

					if($params['post'] != FALSE)
					{
						curl_setopt($ch, CURL_POST, TRUE);
						if(is_array($params['post']))
						{
							$post = http_build_query($params['post']);
						}
						else
						{
							$post = $params['post'];
						}
						curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
					}

					$data = curl_exec($ch);
					curl_close($ch);

					if(is_null($data))
					{
						return false;
					}

					return $data;
				}
				else
				{
					return false;
				}
				break;
			case 1:
				include_once(dirname(__FILE__) . '/Utils/UCLibHttp.php');

				$httpObj = new UCLibHttp($requestURL);
				$httpObj->setTimeOut($timeout);

				$post = FALSE;
				if(is_array($params))
				{
					$httpObj->setPostParam($params);
					$post = TRUE;
				}

				if($post)
				{
					$result = $httpObj->post();
				}
				else
				{
					$result = $httpObj->get();
				}

				if($result)
				{
					return $httpObj->getContent();
				}
				else
				{
					return false;
				}
				break;
			case 2:
				return @file_get_contents($requestURL);
				break;
			default:
				return false;
				break;
		}
	}

	/**
	 * @desc 用于URL的改进Base64编码，它不在末尾填充'='号，并将标准Base64中的「+」和「／」分别改成了「*」和「-」
	 */
	function urltrim_base64_encode($str)
	{
	    $std_based_str = base64_encode($str);
	    return trim(str_replace(array('+', '/'), array('*', '-'), $std_based_str), '=');
	}

	/**
	 * @desc 用于URL的改进Base64编码，它不在末尾填充'='号，并将标准Base64中的「+」和「／」分别改成了「*」和「-」
	 */
	function urltrim_base64_decode($based_str)
	{
	    $padding_length = strlen($based_str)%4;
	    $std_based_str = $based_str;
	    for($i=0; $i<$padding_length; $i++)
	    {
	        $std_based_str .= '=';
	    }
	    $std_based_str = str_replace(array('*', '-'), array('+', '/'), $std_based_str);
	    return base64_decode($std_based_str);
	}

	/**
	 * 判断URL是否合法
	 * @param string $url 需要判断的URL
	 * @return boolean
	 */
	function is_url($url = '')
	{
		$url = trim($url);
		if(strlen($url))
		{
			$r = parse_url($url);
			if(isset($r['scheme']) && isset($r['host']))
			{
				return TRUE;
			}

			return FALSE;
		}

		return FALSE;
	}
	
	/**
	 * 判断邮编是否合法
	 * @param string $zipcode 
	 * @return boolean
	 */
	function is_zipcode($zipcode)
	{
		$zipcode = trim($zipcode);
		if(strlen($zipcode) == 0)
		{
			return FALSE;
		}

		$r = eregi("^[0-9]{6}$", $zipcode);

		return $r ? TRUE : FALSE;
	}

	/**
	 * 判断Email是否合法
	 * @param string $emailAddress 需要判断的邮件地址
	 * @return boolean
	 */
	function is_email($emailAddress)
	{
		$emailAddress = trim($emailAddress);
		if(strlen($emailAddress) == 0)
		{
			return FALSE;
		}

		$r = eregi("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$", $emailAddress);

		return $r ? TRUE : FALSE;
	}

	/**
	 * 判断是否是合法的手机号码
	 */
	function is_mobileNum($mobileNumer)
	{
		$mobileNumer = trim($mobileNumer);
		if(strlen($mobileNumer) != 11)
		{
			return FALSE;
		}

		$r = preg_match('/^((\+?86)|\(\+?86\))?0?1(3|5|8)(\d){9}$/', $mobileNumer);

		return $r ? TRUE : FALSE;
	}

	/**
	 * 判断是否是合法的固定电话号码
	 */
	function is_phoneNum($phoneNum)
	{
		$phoneNum = trim($phoneNum);
		if(strlen($phoneNum) == 0)
		{
			return FALSE;
		}

		$r = preg_match('/^((\+?86)|\(\+?86\))?\-?\d{3,4}\-?\d{7,8}\-?\d+$/', $phoneNum);

		return $r ? TRUE : FALSE;
	}

	/**
	 * 判断是否是合法的QQ号码
	 */
	function is_qqNum($qqNum)
	{
		$qqNum = trim($qqNum);

		$r = preg_match('/^\d{5,}$/', $qqNum);

		return $r ? TRUE : FALSE;
	}

	/**
	 * 获取GET参数
	 * @param string &$cgiParams 存储变量
	 * @param string $cgiParamName 字段名
	 * @param string $defaultValue 默认值
	 * @return boolean
	 */
	function check_cgi_input_get(&$cgiParams, $cgiParamName, $defaultValue = 0)
	{
		return _utils_check_cgi_input($cgiParams, $cgiParamName, $defaultValue, 0);
	}

	/**
	 * 获取POST参数
	 * @param string &$cgiParams 存储变量
	 * @param string $cgiParamName 字段名
	 * @param string $defaultValue 默认值
	 * @return boolean
	 */
	function check_cgi_input_post(&$cgiParams, $cgiParamName, $defaultValue = 0)
	{
		return _utils_check_cgi_input($cgiParams, $cgiParamName, $defaultValue, 1);
	}

	/**
	 * 获取GET/POST参数
	 * @param string &$cgiParams 存储变量
	 * @param string $cgiParamName 字段名
	 * @param string $defaultValue 默认值
	 * @return boolean
	 */
	function check_cgi_input_both(&$cgiParams, $cgiParamName, $defaultValue = 0)
	{
		return _utils_check_cgi_input($cgiParams, $cgiParamName, $defaultValue, 2);
	}

	/**
	 * 获取GET/POST参数
	 * @param string &$cgiParams 存储变量
	 * @param string $cgiParamName 字段名
	 * @param string $defaultValue 默认值
	 * @param int $cgiType 获取方式: 0-GET, 1-POST, 2-BOTH.
	 * @return boolean
	 */
	function _utils_check_cgi_input(&$cgiParams, $cgiParamName, $defaultValue, $cgiType)
	{
		$cgiInput = NULL;

		if($cgiType == 1)
		{
			//使用POST方式获取参数
			$cgiInput = stripslashes(trim($_POST[$cgiParamName]));
		}
		else if($cgiType == 2)
		{
			//两种方式均可
			if(isset($_POST[$cgiParamName]))
			{
				$cgiInput = stripslashes(trim($_POST[$cgiParamName]));
			}
			else
			{
				$cgiInput = stripslashes(trim($_GET[$cgiParamName]));
			}
		}
		else
		{
			//使用GET方式获取参数
			$cgiInput = stripslashes(trim($_GET[$cgiParamName]));
		}

		if(is_null($cgiInput) or $cgiInput == '')
		{
			if(is_numeric($cgiParams))
			{
				$cgiParams = $defaultValue + 0;
			}
			else
			{
				$cgiParams = $defaultValue . '';
			}

			return false;
		}
		else
		{
			if(is_numeric($cgiParams))
			{
				if(!is_numeric($cgiInput))
				{
					$cgiParams = $defaultValue + 0;

					return false;
				}
			}

			$cgiParams = $cgiInput;

			return true;
		}
	}

	/**
	 * 统一化时间格式
	 * 时间差小于60分钟: XX分钟前
	 * 时间差大于60分钟并在昨天0点以内: 今天/昨天 H:i
	 * 时间差在昨天0点以前: Y月m日 H:i
	 * @params string $datetime 任意strtotime()函数可以解析的时间格式
	 * @return string
	 */
	function time_formater($datetime = '')
	{
		$datetime = trim($datetime);
		if(strlen($datetime) == 0)
		{
			return '';
		}

		if(strlen($datetime) <= 10 && is_numeric($datetime))
		{
			$timestamp = $datetime;
		}
		else if(strlen($datetime) == 13 && is_numeric($datetime))
		{
			$timestamp = intval($datetime / 1000);
		}
		else
		{
			$timestamp = strtotime($datetime);
			if($timestamp === FALSE || $timestamp == -1)
			{
				return '';
			}
		}

		$now = time();
		if(date('Y', $timestamp) == date('Y', $now))
		{
			$delta = $now - $timestamp;
			$yesterday_midnight = strtotime(date('Y-m-d', $now - 86400) . '00:00:00');

			if($delta <= 0)
			{
				//如果是当前这一分钟
				$formater = '1分钟前';
			}
			if($delta <= 60 * 60 && $delta > 0)
			{
				//如果是60分钟以内
				$formater = ceil($delta/60) . '分钟前';
			}
			elseif($delta > 60 * 60 && $timestamp >= $yesterday_midnight)
			{
				//说明是在60分钟以前并在昨天0点以内
				$today_midnight = strtotime(date('Y-m-d', $now) . '00:00:00');

				if($timestamp > $today_midnight)
				{
					$day = '今天';
				}
				else
				{
					$day = '昨天';
				}

				$formater = $day . date('H:i', $timestamp);
			}
			else
			{
				//超过昨天0点以前的时间
				$formater = date('m月d日 H:i', $timestamp);
			}
		}
		else
		{
			$formater = date('Y年m月d日 H:i', $timestamp);
		}

		return $formater;
	}

	/**
	 * 统一化时间格式
	 * 时间在当天返回H:i
	 * 时间大于当天返回M月d
	 * @params string $timestamp
	 * @return string
	 */
function time_formater_source($timestamp = ''){	
	$timestamp = trim($timestamp);
	if(strlen($timestamp) == 0)
	{
		return '';
	}

	if(strlen($timestamp) <= 10 && is_numeric($timestamp))
	{
		$timestamp = $timestamp;
	}
	else if(strlen($timestamp) == 13 && is_numeric($timestamp))
	{
		$timestamp = intval($timestamp / 1000);
	}
	else
	{
		$timestamp = strtotime($timestamp);
		if($timestamp === FALSE || $timestamp == -1)
		{
			return '';
		}
	}
	
	$deltatime = time() - $timestamp;
	if($deltatime > 24*3600) {
		$result = date('n月j日', $timestamp);
	} else {
		$result = date('H:i', $timestamp);
	}
	return $result;
}


	/**
	 * 生成统一的全局标示符
	 * @param string $key 索引字段
	 * @return string
	 */
	function gen_uuid($prefix)
	{
		$prefix = trim($prefix);
		$chars = md5(uniqid(mt_rand(), true));
		$uuid  = substr($chars,0,8) . '-';
		$uuid .= substr($chars,8,4) . '-';
		$uuid .= substr($chars,12,4) . '-';
		$uuid .= substr($chars,16,4) . '-';
		$uuid .= substr($chars,20,12);

		return $prefix . $uuid;
	}

	/**
	 * 按照固定字符切割字符串
	 * @param string $str 被切割字符串
	 * @param string $tag 切割tag
	 * @return array
	 */
	function split_string($str, $tag = ' ')
	{
		return explode("$tag", $str);
	}

	/**
	 * 获取客户端IP地址
	 * @return string
	 */
	function get_client_ip()
	{
		if(isset($_SERVER))
		{
			if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			{
				return $_SERVER['HTTP_X_FORWARDED_FOR'];
			}
			elseif(isset($_SERVER['HTTP_CLIENT_IP']))
			{
				return $_SERVER['HTTP_CLIENT_IP'];
			}
			else
			{
				return $_SERVER['REMOTE_ADDR'];
			}
		}
		else
		{
			if(getenv("HTTP_X_FORWARDED_FOR"))
			{
				return getenv( "HTTP_X_FORWARDED_FOR");
			}
			elseif(getenv("HTTP_CLIENT_IP"))
			{
				return getenv("HTTP_CLIENT_IP");
			}
			else
			{
				return getenv("REMOTE_ADDR");
			}
		}

		return '';
	}

	/**
	 * 按照传入的用户ID返回用户的HOME地址
	 * @param string $user 用户ID
	 * @return string
	 */
	 function get_user_home_url($user)
	 {
	 	$url = UC_CONF_UC_DOMAIN.'/home/'.$user;
	 	return $url;
	}

/*
* string get_zodiac_sign(date time)
* 输入：生日 2009-03-09
* 输出：星座名称或者错误
*/

function get_zodiac_sign($date){
  $month = date("m",strtotime($date));
  $day  =  date("d",strtotime($date));
  // 检查参数有效性
  if ($month < 1 || $month > 12 || $day < 1 || $day > 31)
  return false;
  // 星座名称以及开始日期
  $signs = array(
    array( "20" => "宝瓶座"),
    array( "19" => "双鱼座"),
    array( "21" => "白羊座"),
    array( "20" => "金牛座"),
    array( "21" => "双子座"),
    array( "22" => "巨蟹座"),
    array( "23" => "狮子座"),
    array( "23" => "处女座"),
    array( "23" => "天秤座"),
    array( "24" => "天蝎座"),
    array( "22" => "射手座"),
    array( "22" => "摩羯座")
  );
  list($sign_start, $sign_name) = each($signs[(int)$month-1]);
  if ($day < $sign_start)
  list($sign_start, $sign_name) = each($signs[($month -2 < 0) ? $month = 11: $month -= 2]);
  return $sign_name;
}

/*
* sub chinese string
* $content string 要截取的内容
* $length int 截取的长度
* $add Y/N 是否添加...Y添加
*/
function subStrCh($str,$len,$add=true){
	$str_length=strlen($str);
	for($i=0;$i<$len;$i++){
		$temp_str=substr($str,0,1);
		if(ord($temp_str) > 127){
			$i++;
			if($i<$len){
				$new_str[]=substr($str,0,3);
				$str=substr($str,3);
			}
		}else{
			$new_str[]=substr($str,0,1);
			$str=substr($str,1);
		}
	}
	$new_str = join($new_str);
	if($add == true && $str_length > $len){
		$new_str = $new_str.'...';
	}
	return $new_str;
}

/**
 * 生成随机数
 * @param integer $length 生成长度
 * @param $numeric 0为字母数字混合，1为数字
 */
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
	$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	return $hash;
}

/**
 * 创建目录，支持多级
 * @param $dir
 */
function mk_directory($dir){
	return is_dir($dir) or (mk_directory(dirname($dir)) and mkdir($dir, 0777));
}

/******************************************************************
* PHP截取UTF-8字符串，解决半字符问题。
* 英文、数字（半角）为1字节（8位），中文（全角）为3字节
* @return 取出的字符串, 当$len小于等于0时, 会返回整个字符串
* @param $str 源字符串
* $len 左边的子串的长度
****************************************************************/
function utf_substr($str,$len,$add=true) {
	$str_length=strlen($str);
	for($i=0;$i<$len;$i++){
		$temp_str=substr($str,0,1);
		if(ord($temp_str) > 127){
			$i++;
			if($i<$len){
				$new_str[]=substr($str,0,3);
				$str=substr($str,3);
			}
		}else{
			$new_str[]=substr($str,0,1);
			$str=substr($str,1);
		}
	}
	$new_str = join($new_str);
	if($add == true && $str_length > $len){
		$new_str = $new_str.'...';
	}
	return $new_str;
}

/******************************************************************
* 计算用户年龄
* @param date $date 用户生日
* 1981-01-03
****************************************************************/
function user_age($date){
	$age = date('Y',time())-date('Y',strtotime($date)) - 1;
	if (date('m', time()) == date('m', strtotime($date))){
		if (date('d', time()) > date('d', strtotime($date))){
			$age++;
		}
	}elseif (date('m', time()) > date('m', strtotime($date))){
		$age++;
	}
	return $age;
}

/** 评论描述转为表情
  * @param $message需要转换的内容
  * @param $baseUrl图片存放根目录
  * @param return 转换后的内容
  **/
function codeToSmile($message,$baseUrl='')
{
	$smiliesCfg =array(
		array( "code" => "[大笑]", "img" => "1.gif",'alt'=>'大笑' ),
		array( "code" => "[愤怒]", "img" => "2.gif",'alt'=>'愤怒' ),
		array( "code" => "[色]", "img" => "3.gif",'alt'=>'色' ),
		array( "code" => "[耍酷]", "img" => "4.gif" ,'alt'=>'耍酷'),
		array( "code" => "[泪奔]", "img" => "5.gif",'alt'=>'泪奔' ),
		array( "code" => "[晕]", "img" => "6.gif",'alt'=>'晕' ),
		array( "code" => "[衰]", "img" => "7.gif",'alt'=>'衰' ),
		array( "code" => "[茫然]", "img" => "8.gif" ,'alt'=>'茫然'),
		array( "code" => "[吐舌头]", "img" => "9.gif",'alt'=>'吐舌头' ),
		array( "code" => "[眨眼]", "img" => "10.gif" ,'alt'=>'眨眼'),
		array( "code" => "[bye]", "img" => "11.gif" ,'alt'=>'bye'),
		array( "code" => "[闭嘴]", "img" => "12.gif" ,'alt'=>'闭嘴'),
		array( "code" => "[得意]", "img" => "13.gif",'alt'=>'得意' ),
		array( "code" => "[干杯]", "img" => "14.gif",'alt'=>'干杯'),
		array( "code" => "[害羞]", "img" => "15.gif" ,'alt'=>'害羞'),
		array( "code" => "[钱钱]", "img" => "16.gif" ,'alt'=>'钱钱'),
		array( "code" => "[礼物]", "img" => "17.gif" ,'alt'=>'礼物'),
		array( "code" => "[流口水]", "img" => "18.gif" ,'alt'=>'流口水'),
		array( "code" => "[汗]", "img" => "19.gif" ,'alt'=>'汗'),
		array( "code" => "[吃惊]", "img" => "20.gif" ,'alt'=>'吃惊')
	);

	if(!$baseUrl)
	{
		$baseUrl = UC_CONF_STATIC_DOMAIN."/images/face/";
	}

	foreach($smiliesCfg as $val)
	{
		$code = '/' . str_replace(']', '\]', str_replace('[', '\[', $val['code'])) . '/';
		$img = "<img src='".$baseUrl.$val['img']."' title='".$val['alt']."' height='22px' width='22px'/>";
		$message = preg_replace($code, $img , $message);
	}

	$search_arr  = array(
		"/\[url=http:\/\/([-\d\w._~]{1,10})\.sdo.com([^\[\"']*)\](.+?)\[\/url\]/is"
	);
	$replace_arr = array(
		"<a href=\"http://\\1.sdo.com\\2\" target=\"_blank\">\\3</a>"
	);
	$message = preg_replace($search_arr, $replace_arr, $message);

	return  $message ;
}


	/**
	* 将一个二维数组按照多个列进行排序，类似 SQL 语句中的 ORDER BY
	*
	* 用法：
	* @code php
	* $rows = sortByMultiCols($rows, array(
	*     'parent' => SORT_ASC,
	*     'name' => SORT_DESC,
	* ));
	* @endcode
	*
	* @param array $rowset 要排序的数组
	* @param array $args 排序的键
	*
	* @return array 排序后的数组
	*/
    function sortByMultiCols($rowset, $args)
    {
        $sortArray = array();
        $sortRule = '';
        foreach ($args as $sortField => $sortDir)
        {
            foreach ($rowset as $offset => $row)
            {
                $sortArray[$sortField][$offset] = $row[$sortField];
            }
            $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
        }
        if (empty($sortArray) || empty($sortRule))
		{
			return $rowset;
		}
        eval('array_multisort(' . $sortRule . '$rowset);');
        return $rowset;
    }

    function str_insert($str, $i, $substr)
	{
		for($j=0; $j<$i; $j++){
			$startstr .= $str[$j];
		}
		for ($j=$i; $j<strlen($str); $j++){
			$laststr .= $str[$j];
		}
		$str = ($startstr . $substr . $laststr);
		return $str;
	}
	
	/**
	 * 生成指定长度随机数
	 */
	function make_rand_string($len = 16)
	{
		if(!is_numeric($len))
		{
			return FALSE;
		}
		$len = trim($len);
		
		if($len < 1)
		{
			$len = 1;
		}
		
		if($len > 256)
		{
			$len = 256;
		}
		
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		mt_srand((double)microtime()*1000000*getmypid());
		
		$rand_str = '';
		
		while(strlen($rand_str) < $len)
		{
			$rand_str .= substr($chars, (mt_rand()%strlen($chars)), 1);
		}
		return $rand_str;
	}
	
//将 HTML 转换成文本
function htmlText($document){
	$search = array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
                 "'<[\/\!]*?[^<>]*?>'si",           // 去掉 HTML 标记
                 "'([\r\n])[\s]+'",                 // 去掉空白字符
                 "'&(quot|#34);'i",                 // 替换 HTML 实体
                 "'&(amp|#38);'i",
                 "'&(lt|#60);'i",
                 "'&(gt|#62);'i",
                 "'&(nbsp|#160);'i",
                 "'&(iexcl|#161);'i",
                 "'&(cent|#162);'i",
                 "'&(pound|#163);'i",
                 "'&(copy|#169);'i",
                 "'&#(\d+);'e");
	$replace = array ("",
                  "",
                  "\\1",
                  "\"",
                  "&",
                  "<",
                  ">",
                  " ",
                  chr(161),
                  chr(162),
                  chr(163),
                  chr(169),
                  "chr(\\1)");
  $text = preg_replace ($search, $replace, $document);
	return $text;
}

//计算php执行时间
class runtime
{
    var $StartTime = 0;
    var $StopTime = 0;
 
    function get_microtime()
    {
        list($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
    }
 
    function start()
    {
        $this->StartTime = $this->get_microtime();
    }
 
    function stop()
    {
        $this->StopTime = $this->get_microtime();
    }
 
    function spent()
    {
        return round(($this->StopTime - $this->StartTime) * 1000, 1);
    }
 
}

?>